<?php

/**
 * Framework_Module_Browse
 *
 * @author      Ian Szewczyk <roamzero@gmail.com>
 * @copyright   (c) 2007 Ian Szewczyk. All rights reserved.
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @package Modules
 * @filesource
 */

/**
 * Framework_Module_Browse
 *
 * @author Ian Szewczyk <roamzero@gmail.com>
 * @package Modules
 */
class Framework_Module_Browse extends Framework_Module
{
		
	/**
	 * $filter
	 *
	 * @access 		public
	 * @var 		array 		$filter		Filter used to filter database results
	 */
	private $filter = array();

	/**
	 * $navigator
	 *
	 * @access 		public
	 * @var 		object 		$navigator		Instance of Framework_Navigator
	 */
	private $navigator;

	/**
     * __construct
     *
     * Initializes the module: sets the default presenter, the allowed
     * conrollers, and the allowed events
     *
     * @access 		public
     * @return 		void
     */
	public function __construct()
	{
		parent::__construct();
		$this->presenter = 'Smarty';
		 
		 
		// Set outer template
		$this->pageTemplateFile = 'Page.tpl';
		$this->tplFile = 'Browse.tpl';
			
		if ($this->session->browseFilter) {
			$this->filter = $this->session->browseFilter;
		}
			
		// Valid Controllers
		$this->controllers[] = 'Peopletab';
			
		// Valid Events
		$this->validEvents[] = 'viewOwners';
		$this->validEvents[] = 'viewLogins';
			
		$navigator = new Framework_Navigator('/-/Browse', 'browseNavList');
		$navigator->setItem('ownersListItem','/viewOwners','View Local Owners');
		$navigator->setItem('loginsListItem','/viewLogins','View Local Logins');

		$this->navigator = $navigator;
			

		 
	}

	/**
	 * __default
	 *
	 *
	 * @access 		public
	 * @return 		mixed 		boolean true on success, PEAR_Error on failure
	 */
	public function __default()
	{
		return $this->viewOwners();
	}

	/**
	 * viewOwners
	 *
	 *
	 * @access 		public
	 * @return 		mixed 		boolean true on success, PEAR_Error on failure
	 */
	public function viewOwners()
	{
		$this->navigator->setActive('ownersListItem');

		$this->setData('browseNavList', $this->navigator->getNavigation());


		 
		$ownerDB = Framework_DB::dbFactory('Owner');

		if(PEAR::isError($ownerDB)) {
			return $ownerDB;
		}

		$form = Framework_Quickform::factory('browse', 'post', Framework::$request->getBaseHTTPPath().'/-/Browse/');

		// Age Filter
		$ageArray = array();
		for($start = 18; $start <= 99; $start++) {
			$ageArray[$start] = $start;
		}
		$form->addElement('select', 'from', 'From: ', $ageArray);
		$form->addElement('select', 'to', 'To: ', $ageArray);

		// Gender
		$form->addElement('select', 'gender', 'Gender: ', array('b' => 'Both', 'm' => 'Male', 'f' => 'Female'));

		// Relationship Status
		$form->addElement('select', 'relationshipStatus', 'Relationship Status: ', array('a'=>'Any',
		'sn'=> 'Single and Not Available',
		'sa'=> 'Single and Available',
		'ss'=> 'Seeing Someone',
		'm' => 'Married',
		'e' => 'Engaged'));

		// Submit button
		$form->addElement('submit','btnSubmit','Filter People','class="button" id="btnSubmit"');
		 
		// Submit button
		$form->addElement('submit','btnSubmitReset','Reset Filter','class="button" id="btnSubmit"');
		 
		// Filters
		$form->applyFilter('__ALL__','trim');
		 
		// Defaults
		if ($this->session->browseForm) {
			$form->setDefaults($this->session->browseForm);
		}
		 

		 
		// Process form
		if ($form->validate()) {
			$form->process(array($this, 'process'));

		}
		 
		$this->forms['form'] = $form;
		 
		if ($this->filter) {
			$filter = join(' AND ', $this->filter);
		}

		$queryArray = array(
		'sqlKey' => array(
		'select' => 'userName, blurb, siteDomain, avatarURL, dateLastLogin',
		'from'   => 'SiteUser, PersonalInfo',
		'where'  => 'SiteUser.idOwner = PersonalInfo.idOwner AND PersonalInfo.privacy = 3',
		'get'    => 'all'
         	),
		'filter' => $filter,
		'order'  => 'SiteUser.dateLastLogin DESC'
         );

		$result = Framework_DB::dataGridFactory($ownerDB, $queryArray);
		 
		if (!PEAR::isError($result)) {
			$data = $result->getData();
			if (!PEAR::isError($data) && count($data)) {
				$this->setData('results', $data);
				$this->setData('pager', $result->getPager());
			} else {
				$this->setData('noResults', 'No Result');
			}


		} else {
			return $result;
		}
		 
		 
		 
		 
		 
	}

	
	/**
	 * viewLogins
	 *
	 *
	 * @access 		public
	 * @return 		mixed 		boolean true on success, PEAR_Error on failure
	 */
	public function viewLogins()
	{
		 
		 
		$this->navigator->setActive('loginsListItem');

		$this->setData('browseNavList', $this->navigator->getNavigation());
		 
		$ownerDB = Framework_DB::dbFactory('Owner');
		 
		$queryArray = array(
		'sqlKey' => array(
		'select' => 'userName, blurb, siteDomain, avatarURL, dateLastLogin',
		'from'   => 'SiteUser',
		'where'  => 'SiteUser.idSiteUser != 0'
         	),

		'order'  => 'dateLastLogin DESC'
         );

		$result = Framework_DB::dataGridFactory($ownerDB, $queryArray);
		 
		if (!PEAR::isError($result)) {
			$data = $result->getData();
			if (!PEAR::isError($data) && count($data)) {
				$this->setData('results', $data);
				$this->setData('pager', $result->getPager());
			} else {
				$this->setData('noResults', 'No Result');
			}


		} else {
			return $result;
		}
		 
		 
		 
	}

	/**
     * process
     *
     *
     * @access 		public
     * @param 		array		$data		Data to process
     * @return 		string		String to use as formResponse
     */
	public function process($data)
	{
		$this->filter = null;
		 
	    if ($data['from'] && preg_match('/^[0-9]+$/i', $data['from'])){
			$dateTime = $this->dateadd('yyyy', '-'.$data['from'],date("Y-m-d",time())); //date_create($data['from'].' years ago');
			$this->filter[] = 'PersonalInfo.birthDate <= "'.$dateTime .'"';

			if ($data['to'] && preg_match('/^[0-9]+$/i', $data['to'])) {
				$dateTime2 = $this->dateadd('yyyy', '-'.$data['to'],date("Y-m-d",time())); //date_create($data['to'].' years ago');
				$this->filter[] = 'PersonalInfo.birthDate >= "'.$dateTime2.'"';
			}
		}
		 
		if ($data['gender'] && (strcasecmp($data['gender'], 'b') != 0)) {
			$this->filter[] = 'PersonalInfo.gender = "'.mysql_escape_string($data['gender']).'"';
		}
		 
		if ($data['relationshipStatus'] && (strcasecmp($data['relationshipStatus'], 'a') != 0)) {
			$this->filter[] = 'PersonalInfo.relationshipStatus = "'.mysql_escape_string($data['relationshipStatus']).'"';
		}
		 
		// set defaults into into the session
		if ($data['btnSubmitReset']) {
			$this->filter = null;
			$this->session->browseFilter = null;
			$this->session->browseForm = null;

		} else if (count($this->filter)) {
			$this->session->browseFilter = $this->filter;
			$this->session->browseForm = $data;
		}
		 
		 
		 
		 
	}
	
	#$newdate = dateadd("d",-3,"2006-12-12");    #  subtract 3 days from date
	public function dateAdd($interval,$number,$dateTime) {
       
    $dateTime = (strtotime($dateTime) != -1) ? strtotime($dateTime) : $dateTime;      
    $dateTimeArr=getdate($dateTime);
               
    $yr=$dateTimeArr[year];
    $mon=$dateTimeArr[mon];
    $day=$dateTimeArr[mday];
    $hr=$dateTimeArr[hours];
    $min=$dateTimeArr[minutes];
    $sec=$dateTimeArr[seconds];

    switch($interval) {
        case "s"://seconds
            $sec += $number;
            break;

        case "n"://minutes
            $min += $number;
            break;

        case "h"://hours
            $hr += $number;
            break;

        case "d"://days
            $day += $number;
            break;

        case "ww"://Week
            $day += ($number * 7);
            break;

        case "m": //similar result "m" dateDiff Microsoft
            $mon += $number;
            break;

        case "yyyy": //similar result "yyyy" dateDiff Microsoft
            $yr += $number;
            break;

        default:
            $day += $number;
         }      
               
        $dateTime = mktime($hr,$min,$sec,$mon,$day,$yr);
        $dateTimeArr=getdate($dateTime);
       
        $nosecmin = 0;
        $min=$dateTimeArr[minutes];
        $sec=$dateTimeArr[seconds];

        if ($hr==0){$nosecmin += 1;}
        if ($min==0){$nosecmin += 1;}
        if ($sec==0){$nosecmin += 1;}
       
        if ($nosecmin>2){     return(date("Y-m-d",$dateTime));} else {     return(date("Y-m-d G:i:s",$dateTime));}
	}
	

	public function viewDirectory()
	{
		 
	}

	public function saveToDirectory()
	{
		 
	}
	 
	 



}

?>